using UnityEngine;
using System.Collections;
using pumpkin;
using pumpkin.display;
using pumpkin.events;

public class SWFPlayer : MonoBehaviour
{
	public GameObject[] targetObjs;
	public DamageVo[] damages;
	public GameObject attackInitiator;
	
	public enum SwapMode
	{
		Once,
		Loop,
	}
	
	public int Mode {
		get {
			return (int)swapMode;
		}
		set {
			swapMode = (SwapMode)value;
		}
	}
	
	public int FPS {
		get {
			return mcb.fps;
		}set {
			mcb.fps = value;
		}
	}
	
	public int Layer {
		get {
			return layer;
		}set {
			layer = value;
		}
	}
	
	//开始播放后延迟时间//
	public float delayTime = 0.0f;
	public Vector3 offset;
	public SwapMode swapMode = SwapMode.Once;
	public float life;
	public int depth;
	public bool autoDestroy = false;
	int mode;
	int layer;
	MovieClipBehaviour mcb;
	MovieClip movieClip;
	bool startPlay;
	bool hasPlay;
	float startPlayTime;
	Transform mTans;
	int totalFames;
	Vector3 originalScale;
	Renderer mRender;

	// Use this for initialization
	void Awake ()
	{
		gameObject.SetActive (false);
		
		mTans = transform;
		
		mcb = GetComponent<MovieClipBehaviour> ();
		mcb.loop = false;
		movieClip = mcb.movieClip;
		//mcb.enabled = false;
		movieClip.stop ();
		totalFames = movieClip.getTotalFrames ();
		originalScale = transform.localScale;
		
		mRender = renderer;
	}
	
	void Start ()
	{
		
	}
	
	void Update ()
	{
		if (startPlay == false) {
			return;
		}
		
		float currentTime = Time.realtimeSinceStartup;
		
		if (currentTime < startPlayTime + delayTime) {
			mRender.enabled = false;
			return;
		}
		
		mRender.enabled = true;
		
		PlayMovieClip ();
		
		int currentFrame = movieClip.getCurrentFrame ();
		
		if (swapMode == SwapMode.Once) {
			if (currentFrame == totalFames) {
				if (targetObjs != null && damages != null) {
					for (int i = 0; i < targetObjs.Length; i++) {
						FightAction tFightAction = targetObjs[i].GetComponent<FightAction>();
						DamageVo damage = damages[i];
						tFightAction.beAttack(damage);
						tFightAction.AttackInitiator = attackInitiator;
					}
				}
				
				targetObjs = null;
				damages = null;
				
				Stop ();
			}
		} else {
			//循环播放//
		}
	}
	
	public void Play (Vector3 effectPos)
	{
		if (depth == 0) {
			offset = new Vector3 (0, 0, -1);
		} else if (depth == 1) {
			offset = new Vector3 (0, 0, 1);
		}
		
		transform.position = effectPos + offset;
		
		startPlay = true;
		
		startPlayTime = Time.realtimeSinceStartup;
		
		gameObject.SetActive (true);
	}
	
	void Stop ()
	{
		hasPlay = false;
		
		mcb.movieClip.gotoAndStop (1);
		startPlay = false;
		gameObject.SetActive (false);
		
		if(autoDestroy == true)
			Destroy(gameObject);
	}
	
	void PlayMovieClip ()
	{
		if(hasPlay == true) return;
		
		mcb.movieClip.gotoAndPlay (1);
		
		hasPlay = true;
	}
	
	void SetVisable (bool visable)
	{
		gameObject.renderer.enabled = visable;
	}
}
